﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using BiblioWeb.Filters;
using Biblio.Domain;
using Biblio.DataAccess;


namespace BiblioWeb.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        private BiblioDbContext db;
        private SocioRepo socioRepo;
        public AccountController() 
        {
            db  = new BiblioDbContext();
            socioRepo = new SocioRepo(db);
        }
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Cuenta c, string returnUrl)
        {
            Cuenta c2;
            if (WebSecurity.Login(c.NombreUsuario, c.Password, persistCookie: c.Recordarme))
            {
                c2 = db.Cuentas.Where(c3 => c3.NombreUsuario.Equals(c.NombreUsuario)).First();
                if(c2.Tipo.Equals("A"))
                    return RedirectToAction("Index", "Administrador",c2);
                else if (c2.Tipo.Equals("S")) return RedirectToAction("Index", "Socio",c2);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "Nombre de usuario o contraseña incorrectos.");
            return View(c);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(Socio s)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                //!(this.db.UserProfiles.Select(m => m.UserName.Equals(model.Cuenta.UserName, System.StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault()))
                if (!WebSecurity.UserExists(s.Cuenta.NombreUsuario))
                {
                    try
                    {
                        s.Cuenta.Tipo = "S";
                        socioRepo.Agregar(s);
                        WebSecurity.CreateAccount(s.Cuenta.NombreUsuario, s.Cuenta.Password);

                        return RedirectToAction("Index", "Administrador");

                    }
                    catch (MembershipCreateUserException e)
                    {
                        ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                    }
                }
                else { ModelState.AddModelError("", "El nombre de usuario ya existe. Por favor elija otro nombre de usuario."); }
            }

            // If we got this far, something failed, redisplay form
            return View(s);
        }


        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }


        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "El Nombre de usuario ya existe. Por favor, introduzca un nombre de usuario diferente.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
